package com.wisdom.model.dao.hibernate;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.wisdom.exceptions.RoleNotFoundException;
import com.wisdom.model.dao.RoleDao;
import com.wisdom.model.entities.Role;
import javax.annotation.Resource;


@Transactional
@Repository("roleDao")
public class HibernateRoleDao implements RoleDao {
	@Resource
	private HibernateTemplate template;
	
	public void add(Role r) {
		template.save(r);
	}
	public Role getRole(String roleName) throws RoleNotFoundException {
		Role r = new Role();
		r.setRole(roleName);
		
		List<Role> ans = template.findByValueBean("from Role role where role.role = :role", r);
		if (ans.size() == 0)
			throw new RoleNotFoundException();
		return ans.get(0);
	}

	public List<Role> getRoles() {
		List<Role> ans = template.find("from Role role");
		return ans;
	}

	public void remove(Role r) {
		template.delete(r);
	}

	public Role remove(String roleName) throws RoleNotFoundException {
		Role role = getRole(roleName);
		
		remove(role);
		
		return role;
	}
	@Override
	public void update(Role r) {
		template.saveOrUpdate(r);
	}

}
